<?php

$cache_time = 5;
$cache_file = './temp/'.md5(__FILE__).'.html';

if (file_exists($cache_file)) {
    $time = time() - filemtime($cache_file);
    if ($time  < $cache_time) {
        readfile($cache_file);
        exit(0);
    }
}

echo "重新生成缓存文件....<br />", PHP_EOL;

ob_start();

$sql_cache = './temp/sql.cache';
if (file_exists($sql_cache)) {
    echo '正在读取缓存数据...<br />';
    // $data = unserialize(file_get_contents($sql_cache));
    eval('$data='.file_get_contents($sql_cache).';');
} else {
    echo '正在连接数据库生成数据缓存...<br />', PHP_EOL;

    $db = mysqli_connect('localhost', 'root', '123123', 'blog', 3306, '/var/run/mysqld/mysqld.sock');
    $result = mysqli_query($db, 'select * from test');

    while (($row = mysqli_fetch_assoc($result)) !== null) {
        $data[] = $row;
    }
    // file_put_contents($sql_cache, serialize($data));
    file_put_contents($sql_cache, var_export($data, true));
    mysqli_close($db);
}

$title = "学生信息!";

$table = '<table class="table table-border">';
$table .= '<caption>学生信息表</caption>';
$table .= '
<tr>
    <th>ID</th>
    <th>姓名</th>
    <th>年龄</th>
    <th>性别</th>
</tr>';
foreach ($data as $r) {
    $table .= '<tr>';
    foreach ($r as $c) {
        $table .= '<td>'.$c.'</td>';
    }
    $table .= '</tr>';
}
$table .= '</table>';

$html = <<< EOF
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>$title</title>
    <link rel="stylesheet" href="../public/css/bootstrap.min.css" media="all">
</head>
<body>
    $table
</body>
</html>
EOF;

echo $html;

$content = ob_get_contents();
$file = md5(__file__);

file_put_contents('./temp/'.$file.'.html', $content);

ob_end_flush();

